use crate::config::Config;
use crate::message::Message;
use crate::utils::{highlight_json, save_json_to_file};
use eframe::egui;
use rumqttc::v5::mqttbytes::QoS;
use rumqttc::v5::{AsyncClient, MqttOptions};
use serde_json::Value;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};
use tokio::runtime::Runtime;

pub struct MqttApp {
    broker_address: String,
    port: String,
    client_id: String,
    publish_topic: String,
    publish_payload: String,
    subscribe_topic: String,
    received_messages: Arc<Mutex<Vec<Message>>>,
    total_received: Arc<AtomicU64>,
    mqtt_client: Option<AsyncClient>,
    runtime: Runtime,
    connected: bool,
    connection_status: String,
    dark_mode: bool,
    latest_json: Arc<Mutex<Option<String>>>,
    save_success_message: Arc<Mutex<Option<(String, SystemTime)>>>,
    max_messages: usize,
}

impl Default for MqttApp {
    fn default() -> Self {
        let config = Config::load().unwrap_or_else(|e| {
            eprintln!("Failed to load config: {}", e);
            Config::default()
        });

        Self {
            broker_address: config.connection.broker_address,
            port: config.connection.port,
            client_id: config.connection.client_id,
            publish_topic: config.topics.publish_topic,
            publish_payload: config.message.default_payload,
            subscribe_topic: config.topics.subscribe_topic,
            received_messages: Arc::new(Mutex::new(Vec::with_capacity(20))),
            total_received: Arc::new(AtomicU64::new(0)),
            mqtt_client: None,
            runtime: Runtime::new().unwrap(),
            connected: false,
            connection_status: "未连接".to_string(),
            dark_mode: config.ui.dark_mode,
            latest_json: Arc::new(Mutex::new(None)),
            save_success_message: Arc::new(Mutex::new(None)),
            max_messages: 20,
        }
    }
}

impl eframe::App for MqttApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        if self.dark_mode {
            ctx.set_visuals(egui::Visuals::dark());
        } else {
            ctx.set_visuals(egui::Visuals::light());
        }

        self.render_top_panel(ctx);
        self.render_left_panel(ctx);
        self.render_central_panel(ctx);

        ctx.request_repaint();
    }
}

impl MqttApp {
    pub fn connect_mqtt(&mut self) {
        let broker_address = self.broker_address.clone();
        let port = self.port.parse::<u16>().unwrap_or(1883);
        let client_id = self.client_id.clone();
        let received_messages = Arc::clone(&self.received_messages);
        let total_received = Arc::clone(&self.total_received);
        let latest_json = Arc::clone(&self.latest_json);
        let max_messages = self.max_messages;

        let mut mqttoptions = MqttOptions::new(client_id, broker_address, port);
        mqttoptions.set_keep_alive(Duration::from_secs(5));
        mqttoptions.set_max_packet_size(Some(1000 * 1024));

        let (client, mut eventloop) = AsyncClient::new(mqttoptions, 10);
        self.mqtt_client = Some(client);
        self.connected = true;
        self.connection_status = "已连接".to_string();

        if let Ok(mut latest) = self.latest_json.lock() {
            *latest = None;
        }

        self.runtime.spawn(async move {
            loop {
                let event = eventloop.poll().await;
                match event {
                    Ok(rumqttc::v5::Event::Incoming(packet)) => {
                        if let rumqttc::v5::mqttbytes::v5::Packet::Publish(publish) = packet {
                            if let Ok(payload) = String::from_utf8(publish.payload.to_vec()) {
                                let topic_str = String::from_utf8_lossy(&publish.topic).to_string();
                                
                                // 更新接收到的消息列表
                                if let Ok(mut messages) = received_messages.lock() {
                                    if messages.len() >= max_messages {
                                        messages.remove(0);
                                    }
                                    let msg = Message::new(topic_str, payload.clone());
                                    messages.push(msg);
                                    total_received.fetch_add(1, Ordering::Relaxed);
                                }

                                // 更新最新消息
                                if let Ok(mut latest) = latest_json.lock() {
                                    if let Ok(json) = serde_json::from_str::<Value>(&payload) {
                                        let formatted = serde_json::to_string_pretty(&json).unwrap_or(payload.clone());
                                        *latest = Some(formatted);
                                    } else {
                                        *latest = Some(payload.clone());
                                    }
                                }
                            }
                        }
                    }
                    Ok(_) => {}
                    Err(e) => {
                        eprintln!("MQTT Error: {}", e);
                        break;
                    }
                }
            }
        });
    }

    pub fn disconnect(&mut self) {
        self.mqtt_client = None;
        self.connected = false;
        self.connection_status = "已断开".to_string();

        if let Ok(mut latest) = self.latest_json.lock() {
            *latest = None;
        }
    }

    pub fn publish_message(&mut self) {
        if let Some(client) = &self.mqtt_client {
            let topic = self.publish_topic.clone();
            let payload = self.publish_payload.clone();

            if let Ok(_) = serde_json::from_str::<Value>(&payload) {
                let client = client.clone();
                let payload_bytes = payload.into_bytes();
                self.runtime.spawn(async move {
                    if let Err(e) = client
                        .publish(topic, QoS::AtLeastOnce, false, payload_bytes)
                        .await
                    {
                        eprintln!("Failed to publish message: {}", e);
                    }
                });
            }
        }
    }

    pub fn subscribe_topic(&mut self) {
        if let Some(client) = &self.mqtt_client {
            let topic = self.subscribe_topic.clone();
            let client = client.clone();
            self.runtime.spawn(async move {
                client.subscribe(topic, QoS::AtMostOnce).await.unwrap();
            });
        }
    }

    fn render_top_panel(&mut self, ctx: &egui::Context) {
        egui::TopBottomPanel::top("top_panel").show(ctx, |ui| {
            ui.horizontal(|ui| {
                ui.heading("MQTT 客户端");
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if ui
                        .button(if self.dark_mode {
                            "☀️ 浅色模式"
                        } else {
                            "🌙 深色模式"
                        })
                        .clicked()
                    {
                        self.dark_mode = !self.dark_mode;
                    }

                    let status_color = if self.connected {
                        egui::Color32::from_rgb(0, 180, 0)
                    } else {
                        egui::Color32::from_rgb(220, 0, 0)
                    };
                    ui.colored_label(status_color, &self.connection_status);
                });
            });
            ui.add_space(4.0);
            ui.separator();
        });
    }

    fn render_left_panel(&mut self, ctx: &egui::Context) {
        egui::SidePanel::left("connection_panel")
            .resizable(true)
            .default_width(300.0)
            .show(ctx, |ui| {
                ui.add_space(8.0);
                ui.heading("连接设置");
                ui.add_space(8.0);

                ui.horizontal(|ui| {
                    ui.label("地址:");
                    ui.text_edit_singleline(&mut self.broker_address);
                });

                ui.horizontal(|ui| {
                    ui.label("端口:");
                    ui.text_edit_singleline(&mut self.port);
                });

                ui.horizontal(|ui| {
                    ui.label("客户端 ID:");
                    ui.text_edit_singleline(&mut self.client_id);
                });

                ui.add_space(16.0);

                let button_text = if self.connected {
                    "断开连接"
                } else {
                    "连接"
                };
                let button_fill = if self.connected {
                    egui::Color32::from_rgb(180, 50, 50)
                } else {
                    egui::Color32::from_rgb(50, 150, 50)
                };

                if ui
                    .add(
                        egui::Button::new(button_text)
                            .fill(button_fill)
                            .min_size(egui::vec2(ui.available_width(), 32.0)),
                    )
                    .clicked()
                {
                    if self.connected {
                        self.disconnect();
                    } else {
                        self.connect_mqtt();
                    }
                }

                ui.add_space(16.0);
                ui.separator();
                ui.add_space(16.0);

                ui.heading("订阅主题");
                ui.add_space(8.0);

                ui.horizontal(|ui| {
                    ui.label("主题:");
                    ui.text_edit_singleline(&mut self.subscribe_topic)
                        .on_hover_text("输入要订阅的 MQTT 主题");
                });

                ui.add_space(8.0);
                if ui
                    .add_enabled(
                        self.connected,
                        egui::Button::new("订阅")
                            .fill(egui::Color32::from_rgb(70, 70, 180))
                            .min_size(egui::vec2(ui.available_width(), 28.0)),
                    )
                    .clicked()
                {
                    self.subscribe_topic();
                }

                ui.add_space(16.0);
                egui::CollapsingHeader::new("发布消息（调试）")
                    .default_open(false)
                    .show(ui, |ui| {
                        ui.add_space(8.0);

                        ui.horizontal(|ui| {
                            ui.label("主题:");
                            ui.text_edit_singleline(&mut self.publish_topic)
                                .on_hover_text("输入要发布到的 MQTT 主题");
                        });

                        ui.add_space(4.0);
                        ui.label("消息内容 (JSON):");

                        let text_edit = egui::TextEdit::multiline(&mut self.publish_payload)
                            .desired_width(ui.available_width())
                            .desired_rows(8)
                            .hint_text("输入 JSON 格式的消息内容")
                            .font(egui::TextStyle::Monospace)
                            .code_editor()
                            .lock_focus(true);

                        ui.add(text_edit);

                        ui.add_space(8.0);
                        if ui
                            .add_enabled(
                                self.connected,
                                egui::Button::new("发布消息")
                                    .fill(egui::Color32::from_rgb(70, 130, 180))
                                    .min_size(egui::vec2(ui.available_width(), 32.0)),
                            )
                            .clicked()
                        {
                            self.publish_message();
                        }
                    });
    
                    ui.add_space(16.0);
                ui.separator();

                ui.with_layout(egui::Layout::bottom_up(egui::Align::Center), |ui| {
                    ui.add_space(8.0);
                    ui.weak("MQTT Client v0.1.0");
                });
            });
    }

    fn render_central_panel(&mut self, ctx: &egui::Context) {
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.add_space(8.0);
            ui.horizontal(|ui| {
                ui.heading("接收的消息");
                if let Ok(latest) = self.latest_json.lock() {
                    if latest.is_some() {
                        if ui.button("💾 保存最新JSON").clicked() {
                            let latest_json = self.latest_json.clone();
                            let save_success_message = self.save_success_message.clone();
                            self.runtime.spawn(async move {
                                match save_json_to_file(&latest_json) {
                                    Ok(filepath) => {
                                        if let Ok(mut msg) = save_success_message.lock() {
                                            *msg = Some((filepath, SystemTime::now()));
                                        }
                                    }
                                    Err(e) => eprintln!("Failed to save JSON: {}", e),
                                }
                            });
                        }
                    }
                }
            });

            ui.add_space(8.0);
            let latest = self.latest_json.lock().unwrap();
            if let Some(json) = latest.as_ref() {
                ui.add_space(8.0);
                ui.heading("最新JSON消息");
                egui::Frame::dark_canvas(ui.style())
                    .fill(ui.style().visuals.extreme_bg_color)
                    .stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(70, 70, 70)))
                    .rounding(egui::Rounding::same(4.0))
                    .inner_margin(egui::Margin::same(10.0))
                    .show(ui, |ui| {
                        egui::ScrollArea::vertical()
                            .auto_shrink([false; 2])
                            .max_height(200.0)
                            .show(ui, |ui| {
                                highlight_json(json, ui);
                            });
                    });
                ui.add_space(16.0);
            }

            if let Ok(mut msg) = self.save_success_message.lock() {
                if let Some((filepath, timestamp)) = msg.as_ref() {
                    let now = SystemTime::now();
                    let time_diff = now.duration_since(*timestamp).unwrap_or_default();
                    if time_diff.as_secs() < 3 {
                        ui.colored_label(
                            egui::Color32::from_rgb(0, 180, 0),
                            format!("✅ 文件已保存: {}", filepath),
                        );
                    } else {
                        *msg = None;
                    }
                }
            }

            ui.add_space(16.0);
            ui.separator();
            ui.add_space(16.0);

            ui.heading("历史消息");
            ui.add_space(8.0);

            let messages_snapshot = {
                let messages = self.received_messages.lock().unwrap();
                messages.clone()
            };
            let message_count = messages_snapshot.len();
            let total_received = self.total_received.load(Ordering::Relaxed);
            ui.horizontal(|ui| {
                ui.label(format!("当前消息数: {}", message_count));
                ui.separator();
                ui.label(format!("累计接收: {}", total_received));
                if ui.button("🗑️清空历史消息").clicked() {
                    if let Ok(mut messages) = self.received_messages.lock() {
                        messages.clear();
                    }
                }
            });
            ui.add_space(8.0);

            if messages_snapshot.is_empty() {
                ui.weak("暂无消息...");
            } else {
                egui::ScrollArea::vertical()
                    .auto_shrink([false; 2])
                    .show(ui, |ui| {
                        for msg in messages_snapshot.iter().rev() {
                            let mut snippet = String::with_capacity(128);
                            let mut char_count = 0;
                            for ch in msg.payload.chars() {
                                if char_count >= 120 {
                                    snippet.push('…');
                                    break;
                                }
                                snippet.push(ch);
                                char_count += 1;
                            }

                            egui::Frame::dark_canvas(ui.style())
                                .fill(ui.style().visuals.extreme_bg_color)
                                .stroke(egui::Stroke::new(1.0, egui::Color32::from_rgb(70, 70, 70)))
                                .rounding(egui::Rounding::same(4.0))
                                .inner_margin(egui::Margin::same(10.0))
                                .show(ui, |ui| {
                                    ui.horizontal(|ui| {
                                        ui.colored_label(
                                            egui::Color32::from_rgb(120, 180, 120),
                                            format!("主题: {:?}", msg.topic),
                                        );
                                        ui.with_layout(
                                            egui::Layout::right_to_left(egui::Align::Center),
                                            |ui| {
                                                ui.weak(&msg.formatted_timestamp);
                                            },
                                        );
                                    });

                                    ui.add_space(6.0);
                                    ui.label(&snippet);
                                });
                        }
                    });
            }
        });
    }
}
